package cn.onesdream.app.api.service.Impl;

import cn.onesdream.app.api.service.CardService;
import cn.onesdream.app.common.exception.ServiceException;
import cn.onesdream.app.dao.entity.Card;
import cn.onesdream.app.dao.mapper.CardMapper;
import cn.onesdream.app.dao.mapper.UserMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WangShiyu
 * @date 2021/2/7 0:33
 */
@Service
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements CardService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List getCardList(Integer[] cardId) {
        List<Card> cardList = baseMapper.getByIds(cardId);
        return cardList;
    }

    @Override
    public void deleteCard(Integer cardId) {
        baseMapper.deleteById(cardId);
    }

    @Override
    public List<Card> getCardByPlanetId(Integer planetId) {
        QueryWrapper<Card> wrapper = new QueryWrapper<>();
        wrapper.eq("planet_id", planetId);
        List<Card> cardList = baseMapper.selectList(wrapper);
        return cardList;
    }

    @Override
    public Card changeCardInfo(Integer cardId, String title, String content, MultipartFile[] pictures, Byte nameless) throws IOException{
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        File path = new File(ResourceUtils.getURL("classpath").getPath());
        if(!path.exists()){
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(),"static/cardImg/");
        if(!upload.exists()){
            upload.mkdirs();
        }
        String prefix = "/cardImg_";
        String httpUrl = "https://app.onesdream.cn/smallPlanet/static/cardImg/";
        List<String> remoteImgUrls = new ArrayList<>();
        for(int i = 0; i < pictures.length; i++) {
            String originalFilename = pictures[i].getOriginalFilename();
            String fileName = prefix + account + System.currentTimeMillis() + "_" + (i + 1) + originalFilename.substring(originalFilename.lastIndexOf("."));
            String allFileName = upload + fileName;
            File imgFile = new File(allFileName);
            pictures[i].transferTo(imgFile.getAbsoluteFile());
            String remoteImgUrl = httpUrl + fileName;
            remoteImgUrls.add(remoteImgUrl);
        }
        //更新数据库卡片信息
        UpdateWrapper<Card> cardUpdateWrapper = new UpdateWrapper<>();
        Card card = new Card();
        card.setTitle(title);
        card.setContent(content);
        card.setBackimgUrl(JSON.toJSONString(remoteImgUrls));
        card.setNameless(nameless);
        cardUpdateWrapper.lambda()
                .eq(Card::getId, cardId);
        baseMapper.update(card,cardUpdateWrapper);
        card = getCard(cardId);
        return card;
    }

    @Override
    public Card getCard(Integer cardId) {
        Card card = baseMapper.selectById(cardId);
        return card;
    }

    @Override
    public void addCard(String title, String content, Integer userId, Integer planetId, MultipartFile[] pictures, Byte nameless) throws IOException {
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        File path = new File(ResourceUtils.getURL("classpath").getPath());
        if(!path.exists()){
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(),"static/cardImg/");
        if(!upload.exists()){
            upload.mkdirs();
        }
        String prefix = "/cardImg_";
        String httpUrl = "https://app.onesdream.cn/smallPlanet/static/cardImg/";
        List<String> remoteImgUrls = new ArrayList<>();
        for(int i = 0; i < pictures.length; i++) {
            String originalFilename = pictures[i].getOriginalFilename();
            String fileName = prefix + account + System.currentTimeMillis() + "_" + (i + 1) + originalFilename.substring(originalFilename.lastIndexOf("."));
            String allFileName = upload + fileName;
            File imgFile = new File(allFileName);
            pictures[i].transferTo(imgFile.getAbsoluteFile());
            String remoteImgUrl = httpUrl + fileName;
            remoteImgUrls.add(remoteImgUrl);
        }
            Card card = new Card();
            card.setContent(content);
            card.setTitle(title);
            card.setUserId(userId);
            card.setPlanetId(planetId);
            card.setBackimgUrl(JSON.toJSONString(remoteImgUrls));
            card.setNameless(nameless);
            baseMapper.insert(card);
    }

}
